using System;
using System.Collections.Generic;

namespace IppServer.Host
{
    internal sealed class ServerConfig
    {
        internal ServerConfig(string basePrefix, IReadOnlyDictionary<string, string> queueToPrinter)
        {
            BasePrefix = basePrefix;
            QueueToPrinter = queueToPrinter;
        }

        public string BasePrefix { get; }

        public IReadOnlyDictionary<string, string> QueueToPrinter { get; }

        public static ServerConfig Default => new ServerConfig(
            "http://+:8631/printers/",
            new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase));

        public static ServerConfig FromUserInput(string prefix, IReadOnlyCollection<Configuration.PrinterMapping> mappings)
        {
            var normalized = NormalizePrefix(prefix);

            var dictionary = mappings != null
                ? BuildMappingDictionary(mappings)
                : new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            return new ServerConfig(normalized, dictionary.Count > 0 ? dictionary : Default.QueueToPrinter);
        }

        private static Dictionary<string, string> BuildMappingDictionary(IEnumerable<Configuration.PrinterMapping> mappings)
        {
            var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            foreach (var mapping in mappings)
            {
                if (string.IsNullOrWhiteSpace(mapping?.QueueName) || string.IsNullOrWhiteSpace(mapping.PrinterName))
                {
                    continue;
                }

                dict[mapping.QueueName.Trim()] = mapping.PrinterName.Trim();
            }
            return dict;
        }

        private static string NormalizePrefix(string prefix)
        {
            if (string.IsNullOrWhiteSpace(prefix))
            {
                return Default.BasePrefix;
            }

            return prefix.StartsWith("http", StringComparison.OrdinalIgnoreCase)
                ? (prefix.EndsWith("/") ? prefix : $"{prefix.TrimEnd('/')}/")
                : $"http://+:{prefix.Trim()}/printers/";
        }
    }
}

